<template>
  <div class="content-table">
    <el-card>
      <!-- class="project-list-container" -->
      <div>
        <div class="list-h">
          <el-button
            type="primary"
            @click="handleOpen"
            class="add-option"
            v-auth="`/system/manage--add`"
            >添加人员</el-button
          >
          <el-form
            :inline="true"
            class="demo-form-inline"
            :model="formInline"
            ref="formRef"
            @submit.prevent
          >
            <el-form-item label="用户名" prop="userNameLike">
              <el-input
                v-model.trim="formInline.userNameLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="nameLike">
              <el-input
                v-model.trim="formInline.nameLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="单位" prop="companyId">
              <el-input
                v-model.trim="formInline.companyId"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="职称" prop="companyId">
              <el-input
                v-model.trim="formInline.companyId"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="类型" prop="companyId">
              <el-input
                v-model.trim="formInline.companyId"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="角色" prop="companyId">
              <el-input
                v-model.trim="formInline.companyId"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="handleReset">重置</el-button>
              <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-skeleton style="height: 50vh" :rows="8" :loading="loading" animated>
          <el-table
            :data="tableData"
            ref="tableRef"
            border
            v-loading="loading"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          >
            <template #empty>
              <el-empty :image-size="150" description="暂无数据"></el-empty>
            </template>
            <!-- <el-table-column prop="id" label="ID" width="50"></el-table-column> -->
            <el-table-column type="index" label="序号" width="60">
              <template v-slot="scope">
                <span>{{
                  (formInline.pageNum - 1) * formInline.pageSize +
                  scope.$index +
                  1
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="userName" label="用户名"></el-table-column>
            <el-table-column
              prop="name"
              label="姓名"
              width="110"
            ></el-table-column>
            <!-- <el-table-column prop="nickName" label="昵称"></el-table-column> -->
            <!-- <el-table-column prop="email" label="邮箱"></el-table-column> -->
            <!-- <el-table-column prop="address" label="地址"></el-table-column> -->
            <!-- <el-table-column prop="age" label="年龄"></el-table-column> -->
            <el-table-column
              prop="companyName"
              label="单位"
              min-width="120"
            ></el-table-column>
            <!-- <el-table-column prop="deviceId" label="设备ID"></el-table-column> -->
            <el-table-column prop="password" label="职位"></el-table-column>
            <el-table-column prop="password" label="职称"></el-table-column>
            <!-- <el-table-column prop="phoneNum" label="手机号"></el-table-column> -->
            <!-- <el-table-column prop="photo" label="头像"></el-table-column> -->
            <el-table-column
              prop="userType"
              label="类型"
              width="120"
              :formatter="formatterUserType"
            ></el-table-column>
            <el-table-column prop="password" label="角色"></el-table-column>

            <!-- <el-table-column prop="remark" label="备注"></el-table-column> -->

            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定重置该条密码吗？"
                  @confirm="handleResetPassword(row)"
                >
                  <template #reference>
                    <el-button type="text" v-auth="`/system/manage--delete`"
                      >重置密码</el-button
                    >
                  </template>
                </el-popconfirm>
                <el-button
                  type="text"
                  @click="handleEdit(row)"
                  v-auth="`/system/manage--edit`"
                  >编辑</el-button
                >
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定删除该条记录吗？"
                  @confirm="handleDelete(row)"
                >
                  <template #reference>
                    <el-button type="text" v-auth="`/system/manage--delete`"
                      >删除</el-button
                    >
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-skeleton>
      </div>
      <re-pagination
        :total="total"
        v-show="total > 0"
        v-model:page="formInline.pageNum"
        v-model:limit="formInline.pageSize"
        @pagination="handleSearch"
      />
    </el-card>
    <el-dialog
      :title="mode === 'add' ? '添加人员' : '编辑人员'"
      v-model="dialogFormVisible"
      destroy-on-close
      width="600px"
    >
      <user-detail
        @emitClose="emitClose"
        :mode="mode"
        :userInfo="userInfo"
        :companyInfo="companyInfo"
      />
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {
  reactive,
  toRefs,
  ref,
  // inject,
  // watch,
  defineComponent
  // nextTick
} from "vue";
// import { injectKeyCompany } from "./context";
import UserDetail from "./UserDetail.vue";
// import RePagination from "/@/components/RePagination/index.vue";
// import { successMessage, warnMessage } from "/@/utils/message";
import NotifMessage from "/@/utils/message/notification";
import { getUserList, deleteUser, resetPassword } from "/@/api/user";
import { userTypeEnum, ModeType, FormInlineType, UserInfoType } from "../types";
// import { useUserStoreHook } from "/@/store/modules/user";

export default defineComponent({
  name: "UserManage",
  components: {
    UserDetail
    // RePagination
  },

  setup() {
    const formRef = ref<HTMLFormElement | null>(null) as any;
    const tableRef = ref<HTMLTableElement | null>(null) as any;
    // const activeCategory: any = ref(inject(injectKeyCompany));
    // const userHook = useUserStoreHook();
    let loading = ref<boolean>(false);
    let mode = ref<ModeType>("add");
    let dialogFormVisible = ref<boolean>(false);
    let total = ref<number>(0);
    let formInline = reactive<FormInlineType>({
      companyId: null,
      nameLike: "",
      userNameLike: "",
      pageNum: 1,
      pageSize: 10
    });
    let state = reactive({
      tableData: [] as UserInfoType[],
      userInfo: {} as UserInfoType,
      companyInfo: {}
    });

    // 请求表格数据
    async function getTableData(obj: object = {}) {
      // 真实请求待添加
      loading.value = true;
      try {
        const { code, data } = await getUserList(obj);
        if (code === 200) {
          state.tableData = data.list;
          total.value = data.rows;
        }
      } catch (err) {
        console.log(err);
      } finally {
        loading.value = false;
      }
    }
    // 打开添加人员弹窗
    const handleOpen = (): void => {
      dialogFormVisible.value = true;
      mode.value = "add";
      // console.log(activeCategory);
      // if (activeCategory.value.id) {
      // state.companyInfo = activeCategory;
      // }
    };

    const emitClose = (isSubmit: boolean) => {
      dialogFormVisible.value = false;
      if (isSubmit) {
        formInline.pageNum = 1;
        getTableData(formInline);
      }
    };

    // 格式化用户类型
    const formatterUserType = row => {
      return userTypeEnum[row.userType - 1].label;
    };

    // 重置条件
    const handleReset = (): void => {
      formRef.value.resetFields();
    };

    // 根据条件进行搜索
    const handleSearch = (): void => {
      getTableData(formInline);
    };

    // 编辑用户
    const handleEdit = (row): void => {
      dialogFormVisible.value = true;
      mode.value = "edit";
      state.userInfo = row;
    };

    // 删除用户
    const handleDelete = async (item: any) => {
      try {
        const { code, message } = await deleteUser({ id: item.id });
        if (code === 200) {
          // successMessage(`${message}`);
          NotifMessage.success(message);
          getTableData(formInline);
        } else {
          // warnMessage(`${message}`);
          NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };

    // 重置密码
    const handleResetPassword = async (item: any) => {
      try {
        const { code, message } = await resetPassword({ id: item.id });
        if (code === 200) {
          NotifMessage.success(message);
          getTableData(formInline);
        } else {
          NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };

    // 监听左侧树的变化，发起请求
    // watch(activeCategory, newVal => {
    //   if (newVal?.id) {
    //     formInline.companyId = newVal.id;
    //   } else {
    //     formInline.companyId = null;
    //   }
    //   getTableData(formInline);
    // });

    // watch(
    //   () => userHook.isHidden,
    //   () => {
    //     nextTick(() => {
    //       tableRef.value.doLayout();
    //     });
    //   }
    // );

    // 请求数据
    getTableData(formInline);
    return {
      ...toRefs(state),
      total,
      mode,
      tableRef,
      formRef,
      dialogFormVisible,
      loading,
      formInline,
      handleOpen,
      handleReset,
      handleSearch,
      handleEdit,
      handleDelete,
      emitClose,
      formatterUserType,
      handleResetPassword
    };
  }
});
</script>
<style lang="scss" scoped>
// .content-table {
//   width: 100%;
//   height: 100%;
//   padding: 10px;
//   border: 1px solid #e4e7ed;
// }
// .content-table :deep .el-card__body {
//   height: 100%;
// }

// .content-table :deep .el-table__fixed-right-patch {
//   background: #eef1f6;
// }
</style>
